package com.edu.hre.common.ajax;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.edu.hre.common.cache.PassiveDynaCache;
import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.RequestUtils;
import com.edu.hre.common.utils.StringConstants;
import com.edu.hre.db.pojo.HreEmployee;
import com.edu.hre.db.pojo.HreLeaveRequest;
import com.edu.hre.db.pojo.HreSubunit;
import com.edu.hre.db.pojo.HreSurveyEmpAnswer;
import com.edu.hre.db.pojo.HreSurveyTopic;
import com.edu.hre.db.pojo.HreUser;
import com.edu.hre.db.pojo.HreUserRoleScreen;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.action.survey.SurveyTakeListAction;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

/**
 * Servlet implementation class GetNotification
 */
public class GetNotification extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	private static final PassiveDynaCache passiveDynaCache = BeanFinder.getBean(PassiveDynaCache.BEAN_NAME, PassiveDynaCache.class);
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GetNotification() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			//CommonUtils.println(CommonUtils.getSourceCodeLocation());
			if("1".equals(request.getParameter("mode"))){
				sleep(3000);
			}
			String responseText = "";
			if(request.getSession(false) == null){
				return;
			}
			HreEmployee employee = (HreEmployee) request.getSession().getAttribute(RequestUtils.Attribute.EMPLOYEE_INFO);
			HreUser user = (HreUser) request.getSession().getAttribute(RequestUtils.Attribute.USER_INFO);
			//CommonUtils.println("employee.getEmpNumber(): " + user.getEmpNumber());
			//CommonUtils.println("user.getUserRoleId(): " + user.getUserRoleId());
			if (showNotificationLeaveApproval(request, user)) {
				responseText += ";targetLeaveApprove";
			}
			if (showNotificationTakeSurvey(request, user, employee)) {
				responseText += ";targetSurveyTakeList";
			}
			if (responseText.startsWith(";")) {
				responseText = responseText.replaceFirst(";", "");
			}
			response.getWriter().write(responseText);
		} catch (Exception e) {
			//CommonUtils.println(e.getMessage());
		}
	}
	
	private void sleep(){
		sleep(1000);
	}
	
	private void sleep(int i){
		try {
			Thread.sleep(i);
		} catch (Exception e) {
		}
	}

	private boolean showNotificationLeaveApproval(HttpServletRequest request, HreUser user) {
		String key = RequestUtils.Attribute.LEAVE_APPROVAL_NOTIFICATION + user.getEmpNumber();
		try {
			Boolean haveNotification = (Boolean) passiveDynaCache.getCachedItem(key);
			if (haveNotification == null) {
				HreUserRoleScreen userRoleScreen = baseService.getFirstPojoAnd(new String[] { "userRoleId", "actionName" }, new int[] {
						Compare.EQUAL, Compare.EQUAL }, new Object[] { user.getUserRoleId(), "leaveApprove" }, HreUserRoleScreen.class);
				if (userRoleScreen != null && userRoleScreen.isCanRead()) {
					HreLeaveRequest leaveRequest = baseService.getFirstPojoAnd(new String[] { "approved", "supervisorNum" }, new int[] {
							Compare.IS_NULL, Compare.EQUAL }, new Object[] { null, user.getEmpNumber() }, HreLeaveRequest.class);
					if (leaveRequest != null) {
						passiveDynaCache.setCachedItem(key, PassiveDynaCache.TIMEOUT_3_HOURS, true);
						return true;
					}  
				}
			} else if (haveNotification == true) {
				passiveDynaCache.setCachedItem(key, PassiveDynaCache.TIMEOUT_3_HOURS, true);
				return true;
			}  
		} catch (Exception e) {
			//CommonUtils.println(e.getMessage());
		}
		passiveDynaCache.setCachedItem(key, PassiveDynaCache.TIMEOUT_3_HOURS, false);
		return false;
	}

	private boolean showNotificationTakeSurvey(HttpServletRequest request, HreUser user, HreEmployee employee) {
		String key = RequestUtils.Attribute.TAKE_SURVEY_NOTIFICATION + user.getEmpNumber();
		try {
			Boolean haveNotification = (Boolean) passiveDynaCache.getCachedItem(key);
			if (haveNotification == null) {
				HreUserRoleScreen userRoleScreen = baseService.getFirstPojoAnd(new String[] { "userRoleId", "actionName" }, new int[] {
						Compare.EQUAL, Compare.EQUAL }, new Object[] { user.getUserRoleId(), "surveyTakeList" }, HreUserRoleScreen.class);
				if (userRoleScreen != null && userRoleScreen.isCanRead()) {
					List<HreSurveyTopic> listTopic = null;
					if (employee != null && employee.getWorkStation() != null && employee.getWorkStation() > 0) {
						List<Integer> listIdSubunit = new ArrayList<Integer>();
						HreSubunit subunit = baseService.getPojo(employee.getWorkStation(), HreSubunit.class);
						SurveyTakeListAction.getListParentsSubunit(subunit, listIdSubunit);
						//CommonUtils.println("List<Integer> listIdSubunit = " + listIdSubunit.toArray());
						listTopic = SurveyTakeListAction.getListTopic(listIdSubunit, 1000, 0);
					} else {
						listTopic = baseService.getPojosAnd(new String[] { "subunitId", "endDate" }, new int[] { Compare.EQUAL, Compare.GREATER },
								new Object[] { 1, new Date() }, new String[] { "startDate" }, new Boolean[] { true }, 1000, 0, HreSurveyTopic.class);
					}
					for (int i = 0; listTopic != null && i < listTopic.size(); i++) {
						boolean alowUpdate = true;
						boolean taken = false;
						HreSurveyTopic topic = listTopic.get(i);
						HreSurveyEmpAnswer ans = baseService.getFirstPojoAnd(new String[] { "userId", "topicId" }, new int[] { Compare.EQUAL,
								Compare.EQUAL }, new Object[] { user.getId(), topic.getId() }, HreSurveyEmpAnswer.class);
						if (topic.getStartDate().compareTo(new Date()) >= 0) {
							alowUpdate = false;
						}
						if (ans != null) {
							taken = true;
							alowUpdate = false;
						} else {
							taken = false;
						}
						if (alowUpdate && !taken) {
							passiveDynaCache.setCachedItem(key, PassiveDynaCache.TIMEOUT_3_HOURS, true);
							return true;
						} 
					} 
				}
			} else if (haveNotification == true) {
				passiveDynaCache.setCachedItem(key, PassiveDynaCache.TIMEOUT_3_HOURS, true);
				return true;
			}  
		} catch (Exception e) {
			//CommonUtils.println(e.getMessage());
		}
		passiveDynaCache.setCachedItem(key, PassiveDynaCache.TIMEOUT_3_HOURS, false);
		return false;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	private HttpSession getSession(final String sessionId) {
		final ServletContext context = getServletContext();
		final HttpSession session = (HttpSession) context.getAttribute(sessionId);
		return session;
	}
}
